import React, {
  useContext,
  createContext,
  useState,
  ReactNode,
  useCallback,
} from 'react'

export type IData = {tokenName?: number | string; tokenName2?: number | string}
type ILayoutContext = {
  data: IData
  updateData?: (key: keyof IData, value: IData[keyof IData]) => void
} & IData
type IProvider = {children: ReactNode}

export const LayoutContext = createContext<ILayoutContext>({
  data: {},
  updateData: (key: keyof IData, value: IData[keyof IData]) => {
    console.log(key, value, 'key,value')

    return {key, value}
  },
})

export const useLayoutContext = (): ILayoutContext => {
  return useContext(LayoutContext)
}

export const LayoutProvider: React.FC<IProvider> = ({children}) => {
  const [data, setData] = useState<IData>({})

  const handleUpdate = useCallback(
    (key: keyof IData, value: IData[keyof IData]) => {
      setData(prevData => ({
        ...prevData,
        [key]: value,
      }))
    },
    []
  )

  return (
    <LayoutContext.Provider value={{data, updateData: handleUpdate}}>
      {children}
    </LayoutContext.Provider>
  )
}
